from flask import current_app
from flask import render_template
from flask import request, jsonify

from cyds.models import News
from . import news_blu


@news_blu.route('/list')
def news_all():
    """所有新闻"""

    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=403, errmsg="参数错误")

    try:
        paginate = News.query.filter().order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=404, errmsg="数据查询错误")

    # 取到当前页的数据
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news_list in news_model_list:
        news_dict = {
            "id": news_list.id,
            "title": news_list.title,
            "content": news_list.content,
            "image_url": news_list.image_url
        }
        news_dict_li.append(news_dict)

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }
    # return jsonify(errno=200, errmsg="完成", data=data)

    return render_template("front/news_list.html", data=data)


@news_blu.route('/<int:news_id>')
def news_detail(news_id):
    """新闻详情"""

    try:
        new = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

        return jsonify(errno=400, errmsg="查询错误")

    if not new:
        return jsonify(errno=400, errmsg="新闻不存在")

    image_url = "/static/photo_video/image/" + new.image_url

    data = {
        "id": new.id,
        "title": new.title,
        "content": new.content,
        "image_url": image_url
    }

    return render_template("front/news_detail.html", data=data)

